﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.AddressBook
{
    /// <summary>CCPSIP_063：通訊錄2.0 API</summary>
    /// idHeader = 裝置 UUID 前八碼。iOS 請使用 [CCPCrypto getIdHeader] 呼叫。
    /// checkcode = 裝置限時驗證碼。iOS 請使用 [CCPCrypto getCheckcode] 呼叫。
    /// GotoTier = 欲取得的資料層別，Tier：【Location】→【Department】→【PeopleOrNonPeople】→【DetailInfo】
    /// L_Code = 地點代號，欲取得【Department】以下層級時需要傳入。
    /// D_Code = 部門代號，欲取得【PeopleOrNonPeople】以下層級時需要傳入。
    /// PPS_Code = 員工編號，欲取得【DetailInfo】以下層級需要傳入。
    /// N_Name = 分機地點名稱，欲取得【DetailInfo】且D_Code為【Others】時需要傳入。

    public class get_address_book : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            List<string> Tier = new List<string> { "Location", "Department", "PeopleOrNonPeople", "DetailInfo" };

            try
            {
                //【01】取得POST參數，驗證身分
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string GotoTier = req.Form["GotoTier"];
                string L_Code = req.Form["L_Code"];
                string D_Code = req.Form["D_Code"];
                string PPS_Code = req.Form["PPS_Code"];
                string N_Name = req.Form["N_Name"];

                SipUserInfo UserInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (UserInfo == null)
                    throw new Exception("Error_01: Cannot identify this device.");  //無法識別此裝置

                if (!Tier.Contains(GotoTier))
                    throw new Exception("Error_02: Parameter error.");  //GotoTier參數錯誤

                //【02】取得使用者Addressbook權限
                //【02-1】判斷使用者SIP註冊型態, CCP, CCP_MG, CCP_HQ, CCP_ABROAD才看的到通訊錄
                OracleAddressBookKit.Right UserRight = new OracleAddressBookKit.Right();
                if (UserInfo.UserType.StartsWith("CCP"))
                {
                    //【02-2】檢查註冊資訊
                    if (String.IsNullOrEmpty(UserInfo.PPS_CODE) || String.IsNullOrEmpty(UserInfo.DEPT_NO))
                        throw new Exception("Error_03: SIP registration info error.");

                    //【02-3】判斷使用者通訊錄權限(EMP_DATA, A1)
                    if (GotoTier != Tier[0])     //看Location階層不限權限
                        UserRight = OracleAddressBookKit.GetUserRight(UserInfo);
                }
                else
                {
                    throw new Exception("Error_04: Not a CCP User.");
                }

                //【03】取得呼叫階層列表
                OracleAddressBookKit.TierObject TierObject = new OracleAddressBookKit.TierObject();
                Object ReturnObject = new Object();

                if (GotoTier == Tier[0])    //Location
                {
                    TierObject.Tier = GotoTier;
                    TierObject.NextTier = Tier[1];
                    TierObject.List = OracleAddressBookKit.GetLocationList();
                    ReturnObject = TierObject;
                }
                else if (GotoTier == Tier[1])   //Department
                {
                    if (String.IsNullOrEmpty(L_Code))
                        throw new Exception("Error_02: Parameter error.");

                    //TODO:
                    //檢查L_Code是否存在
                    TierObject.Tier = GotoTier;
                    TierObject.PreviousTier = Tier[0];
                    TierObject.NextTier = Tier[2];
                    TierObject.List = OracleAddressBookKit.GetDepartmentsList(UserRight, L_Code);
                    ReturnObject = TierObject;
                }
                else if (GotoTier == Tier[2])   //People or NonPeople
                {
                    if (String.IsNullOrEmpty(L_Code) || String.IsNullOrEmpty(D_Code))
                        throw new Exception("Error_02: Parameter error.");

                    //TODO:
                    //檢查L_Code, D_Code是否存在

                    if (D_Code == "Others")
                    {
                        TierObject.Tier = GotoTier;
                        TierObject.PreviousTier = Tier[1];
                        TierObject.NextTier = Tier[3];
                        TierObject.List = OracleAddressBookKit.GetNonPeopleList(L_Code, D_Code);
                        ReturnObject = TierObject;
                    }
                    else
                    {
                        if (D_Code == "Abroad")
                        {
                            TierObject.Tier = GotoTier;
                            TierObject.PreviousTier = Tier[1];
                            TierObject.NextTier = Tier[3];
                            TierObject.List = OracleAddressBookKit.GetAbroadPeopleList(L_Code, D_Code);
                            ReturnObject = TierObject;
                        }
                        else
                        {
                            //TODO:
                            //若傳入A1則檢查A1權限

                            TierObject.Tier = GotoTier;
                            TierObject.PreviousTier = Tier[1];
                            TierObject.NextTier = Tier[3];
                            TierObject.List = OracleAddressBookKit.GetPeopleList(L_Code, D_Code);
                            ReturnObject = TierObject;
                        }
                    }
                }
                else if (GotoTier == Tier[3])
                {
                    if (String.IsNullOrEmpty(L_Code) || String.IsNullOrEmpty(D_Code))
                        throw new Exception("Error_02: Parameter error.");

                    if (!String.IsNullOrEmpty(PPS_Code) && String.IsNullOrEmpty(N_Name))
                    {
                        TierObject.Tier = GotoTier;
                        TierObject.PreviousTier = Tier[2];
                        TierObject.List = OracleAddressBookKit.GetPeopleDetailInfo(L_Code, D_Code, PPS_Code, UserInfo, UserRight);
                        ReturnObject = TierObject;
                    }
                    else if (!String.IsNullOrEmpty(N_Name) && String.IsNullOrEmpty(PPS_Code))
                    {
                        TierObject.Tier = GotoTier;
                        TierObject.PreviousTier = Tier[2];
                        TierObject.List = OracleAddressBookKit.GetNonPeopleDetailInfo(L_Code, D_Code, N_Name);
                        ReturnObject = TierObject;
                    }
                    else
                        throw new Exception("Error_02: Parameter error.");
                }
                else
                    throw new Exception("Error_02: Parameter error.");

                //【99】回傳結果
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(ReturnObject);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}